<template>
  <div class="id-selector">
    <el-input
      v-model="displayValue"
      :placeholder="placeholder"
      :disabled="true"
      class="selector-input"
    >
      <el-button
        slot="append"
        icon="el-icon-search"
        @click="openDialog"
        :disabled="disabled"
      ></el-button>
    </el-input>
    
    <!-- 选择对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="800px"
      append-to-body
    >
      <!-- 搜索条件 -->
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
        <el-form-item :label="searchLabel" prop="searchField">
          <el-input
            v-model="queryParams.searchField"
            :placeholder="searchPlaceholder"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 数据表格 -->
      <el-table
        ref="dataTable"
        v-loading="loading"
        :data="dataList"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        highlight-current-row
      >
        <el-table-column type="selection" width="55" align="center" v-if="multiple" />
        <el-table-column :label="idLabel" :prop="idField" width="120" />
        <el-table-column :label="nameLabel" :prop="nameField" show-overflow-tooltip />
        <el-table-column v-for="col in extraColumns" :key="col.prop" :label="col.label" :prop="col.prop" show-overflow-tooltip />
      </el-table>
      
      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
      
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmSelection" :disabled="!hasSelection">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'IdSelector',
  props: {
    // 当前值
    value: {
      type: [String, Number, Array],
      default: null
    },
    // 是否多选
    multiple: {
      type: Boolean,
      default: false
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false
    },
    // 占位符
    placeholder: {
      type: String,
      default: '请选择'
    },
    // 对话框标题
    dialogTitle: {
      type: String,
      default: '选择数据'
    },
    // API函数
    apiFunction: {
      type: Function,
      required: true
    },
    // 获取单个数据的API函数
    getApiFunction: {
      type: Function,
      default: null
    },
    // ID字段名
    idField: {
      type: String,
      default: 'id'
    },
    // 名称字段名
    nameField: {
      type: String,
      default: 'name'
    },
    // ID列标签
    idLabel: {
      type: String,
      default: 'ID'
    },
    // 名称列标签
    nameLabel: {
      type: String,
      default: '名称'
    },
    // 搜索字段标签
    searchLabel: {
      type: String,
      default: '名称'
    },
    // 搜索占位符
    searchPlaceholder: {
      type: String,
      default: '请输入名称'
    },
    // 额外显示的列
    extraColumns: {
      type: Array,
      default: () => []
    },
    // 额外的查询参数
    extraParams: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      dialogVisible: false,
      loading: false,
      dataList: [],
      total: 0,
      selectedRows: [],
      currentRow: null,
      displayValue: '',
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        searchField: null
      }
    }
  },
  computed: {
    hasSelection() {
      if (this.multiple) {
        return this.selectedRows.length > 0
      } else {
        return this.currentRow !== null
      }
    }
  },
  watch: {
    value: {
      handler(newVal) {
        this.updateDisplayValue(newVal)
      },
      immediate: true
    }
  },
  methods: {
    // 打开选择对话框
    openDialog() {
      this.dialogVisible = true
      this.resetQuery()
      this.getList()
      // 在获取数据后设置默认选中状态
      this.$nextTick(() => {
        this.setDefaultSelection()
      })
    },
    
    // 获取数据列表
    getList() {
      this.loading = true
      // 构建查询参数，将searchField映射到对应的字段名
      const params = { ...this.queryParams, ...this.extraParams }
      if (params.searchField && this.nameField) {
        params[this.nameField] = params.searchField
        delete params.searchField
      }
      this.apiFunction(params).then(response => {
        this.dataList = response.rows || response.data || []
        this.total = response.total || 0
        this.loading = false
        // 数据加载完成后设置默认选中状态
        this.$nextTick(() => {
          this.setDefaultSelection()
        })
      }).catch(() => {
        this.loading = false
      })
    },
    
    // 搜索
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    
    // 重置搜索
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        searchField: null
      }
      // 不重置选中状态，保持当前选中的值
      if (this.$refs.queryForm) {
        this.$refs.queryForm.resetFields()
      }
    },
    
    // 多选变化
    handleSelectionChange(selection) {
      this.selectedRows = selection
    },
    
    // 行点击
    handleRowClick(row) {
      if (!this.multiple) {
        this.currentRow = row
      }
    },
    
    // 确认选择
    confirmSelection() {
      if (this.multiple) {
        const ids = this.selectedRows.map(row => row[this.idField])
        const names = this.selectedRows.map(row => row[this.nameField]).join(', ')
        this.displayValue = names
        this.$emit('input', ids)
        this.$emit('change', ids, this.selectedRows)
      } else {
        if (this.currentRow) {
          this.displayValue = this.currentRow[this.nameField]
          this.$emit('input', this.currentRow[this.idField])
          this.$emit('change', this.currentRow[this.idField], this.currentRow)
        }
      }
      this.dialogVisible = false
    },
    
    // 更新显示值
    async updateDisplayValue(value) {
      if (!value) {
        this.displayValue = ''
        return
      }
      
      // 检查getApiFunction是否存在
      if (!this.getApiFunction) {
        console.warn('getApiFunction is not defined')
        this.displayValue = ''
        return
      }
      
      try {
        if (this.multiple && Array.isArray(value)) {
          // 多选模式
          const names = []
          for (const id of value) {
            const response = await this.getApiFunction(id)
            const data = response.data || response
            if (data && data[this.nameField]) {
              names.push(data[this.nameField])
            }
          }
          this.displayValue = names.join(', ')
        } else {
          // 单选模式
          const response = await this.getApiFunction(value)
          const data = response.data || response
          if (data && data[this.nameField]) {
            this.displayValue = data[this.nameField]
          } else {
            this.displayValue = ''
          }
        }
      } catch (error) {
        console.error('获取显示名称失败:', error)
        this.displayValue = ''
      }
    },
    
    // 设置默认选中状态
    setDefaultSelection() {
      if (!this.value) return
      
      if (this.multiple && Array.isArray(this.value)) {
        // 多选模式：根据当前值设置选中行
        this.selectedRows = this.dataList.filter(row => 
          this.value.includes(row[this.idField])
        )
        // 设置表格选中状态
        this.$nextTick(() => {
          if (this.$refs.dataTable) {
            this.$refs.dataTable.clearSelection()
            this.selectedRows.forEach(row => {
              this.$refs.dataTable.toggleRowSelection(row, true)
            })
          }
        })
      } else {
        // 单选模式：根据当前值设置当前行
        this.currentRow = this.dataList.find(row => 
          row[this.idField] === this.value
        ) || null
      }
    }
  }
}
</script>

<style scoped>
.id-selector {
  width: 100%;
}

.selector-input {
  width: 100%;
}

.dialog-footer {
  text-align: right;
}
</style>